package com.alibaba.citrus.ots.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.util.CalculatePercentage;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.ots.sales.plan.api.statistics.SalesPlanStatService;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.EditSalesPlanLineRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.QuerySalesPlanLineRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanDetailBatchQueryRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SubmitSalesPlanLineRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.UpdateAdjustCountRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.UpdateTaskCountRequest;
import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.ots.sales.plan.functions.salesplan.SalesPlanLineEntity;
import com.alibaba.citrus.ots.sales.plan.model.SalesPlanLineStatusEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.ots.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.ots.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */
@Component
public class SalesPlanLineWriteServiceImpl implements SalesPlanLineWriteService {

    private final static Logger log= LoggerFactory.getLogger(SalesPlanLineWriteServiceImpl.class);

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanQueryService salesPlanQueryService;

    @Resource
    private SalesPlanStatService salesPlanStatService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Override
    @FacadeInvoker
    public Result<String> createSalesPlanLine(SalesPlanLineSDO salesPlanLineSdo) {
        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(salesPlanLineSdo);
        String lastInsertId = salesPlanLineEntity.doCreate();
        return Result.success(lastInsertId);
    }

    @Override
    @FacadeInvoker
    @EpochTransactional(appCode = "bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<String> batchCreateSalesPlanLine(List<SalesPlanLineSDO> salesPlanLineSdoList) {
        if (salesPlanLineSdoList.size() == 0) {
            throw new FacadeException("OTS-02-002-02-15-010");
        }
        //planId+客户收收获地址编码+货品编码查询重复数据
        Set<String> planIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getPlanId).collect(Collectors.toSet());
        Set<String> customerAddressSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        salesPlanDetailBatchQueryRequest.setPlanIds(Lists.newArrayList(planIdSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanDetailBatchQueryRequest.setCustomerAddressIds(Lists.newArrayList(customerAddressIdSet));
        }
        salesPlanDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddressSet));
        salesPlanDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));

        List<SalesPlanLineSDO> salesPlanLineSDOS = salesPlanLineRepository.batchQueryDetailByIds(salesPlanDetailBatchQueryRequest);
        if (salesPlanLineSDOS.size() > 0) {
            throw new FacadeException("OTS-02-002-02-15-017");
        }
        //获取并设置合同量数据
        salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(salesPlanLineSdoList);
        //创建有总量时，对总量三比均衡
        batchCreateSalesPlanLineListConverter(salesPlanLineSdoList);
        return Result.success(salesPlanLineRepository.batchCreateSalesPlanLine(salesPlanLineSdoList));
    }

    private void batchCreateSalesPlanLineListConverter(List<SalesPlanLineSDO> salesPlanLineSdoList) {
        String planId = salesPlanLineSdoList.stream().findFirst().get().getPlanId();
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(planId);
        SalesPlanSDO salesPlan = salesPlanQueryService.getSalesPlan(querySalesPlanRequest).getResult();
        if (Objects.isNull(salesPlan)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        BigDecimal sum = salesPlan.getMonthFirstProprtion().add(salesPlan.getMonthMiddleProprtion()).add(salesPlan.getMonthLastProprtion());
        if (new BigDecimal(100).compareTo(sum) == 0) {
            //月度计划有配置三旬比例均衡
            salesPlanLineSdoList.forEach(salesPlanLineSDO -> {
                //创建传总量需要三比均衡
                if (salesPlanLineSDO.getMonthCount() > 0 && Optional.ofNullable(salesPlanLineSDO.getIsBalanced()).orElse(true)) {
                    //月度计划有配置三旬比例均衡
                    //上旬计划量
                    BigDecimal monthFirstProprtion = salesPlan.getMonthFirstProprtion();
                    BigDecimal firstCount = monthFirstProprtion.multiply(new BigDecimal(Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)));
                    Integer monthFirstCount = firstCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    salesPlanLineSDO.setMonthFirstCount(monthFirstCount);

                    //下旬计划量
                    BigDecimal monthLastProprtion = salesPlan.getMonthLastProprtion();
                    BigDecimal LastCount = monthLastProprtion.multiply(new BigDecimal(Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)));
                    Integer monthLastCount = LastCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    salesPlanLineSDO.setMonthLastCount(monthLastCount);

                    //中旬计划量
                    Integer monthMiddleCount = salesPlanLineSDO.getMonthCount() - (monthFirstCount + monthLastCount);
                    salesPlanLineSDO.setMonthMiddleCount(monthMiddleCount);
                    //传总量 状态为已完成(小程序)
                    salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
                }
                //计算折前计划金额
                long costInsuranceFreight = Objects.nonNull(salesPlanLineSDO.getCostInsuranceFreight()) ? salesPlanLineSDO.getCostInsuranceFreight() : 0;
                long beforeMonthMoney = salesPlanLineSDO.getMonthCount() * costInsuranceFreight;
                salesPlanLineSDO.setBeforeMonthMoney(beforeMonthMoney);
                //计算折后计划金额  折后计划金额=折前计划金额*(1-预估价格折扣率)
                salesPlanLineSDO.calculateMonthMoney(salesPlan.getEstimateDiscount());
                //合同差量  合同差量=month_count（计划数量）-month_contract_count（合同量）
                Integer contractDifferenceCount = salesPlanLineSDO.getMonthCount() - salesPlanLineSDO.getMonthContractCount();
                salesPlanLineSDO.setContractDifferenceCount(contractDifferenceCount);
                //合同差金额 合同差金额=计划折前合同金额 -计划折前金额
                long contractDifferenceMoney = salesPlanLineSDO.getBeforeMonthContractMoney() - beforeMonthMoney;
                salesPlanLineSDO.setContractDifferenceMoney(contractDifferenceMoney);
                //计算折前满足度 折前满足度=折前计划金额/折前合同金额
                BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(beforeMonthMoney, salesPlanLineSDO.getBeforeMonthContractMoney());
                salesPlanLineSDO.setBeforeContractSatisfaction(beforeContractSatisfaction);
                //计算折后满足度  折后满足度 = 折后计划金额/折后合同金额
                BigDecimal contractSatisfaction = CalculatePercentage.retainTwo(salesPlanLineSDO.getMonthMoney(), salesPlanLineSDO.getMonthContractMoney());
                salesPlanLineSDO.setContractSatisfaction(contractSatisfaction);

                //到岸折前金额
                long outboundPrice = Objects.nonNull(salesPlanLineSDO.getOutboundPrice()) ? salesPlanLineSDO.getOutboundPrice() : 0;
                long beforeMonthOutboundMoney = salesPlanLineSDO.getMonthCount() * outboundPrice;
                salesPlanLineSDO.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
                salesPlanLineSDO.calculateMonthOutboundMoney(salesPlan.getEstimateDiscount());
                //总量不为0时，状态为已完成
                if (0 != Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)){
                    salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
                }else {
                    salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.DRAFT.getStatus());
                }
            });
        }
    }

    /**
     * 失焦保存
     */
    @Override
    @FacadeInvoker
    public Result<SalesPlanLineSDO> editSalesPlanLine(EditSalesPlanLineRequest editSalesPlanRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(editSalesPlanRequest.getId());
        SalesPlanLineSDO salesPlanLineSDO = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
        if (null == salesPlanLineSDO) {
            return null;
        }
        String planId = salesPlanLineSDO.getPlanId();
        SalesPlanLineSDO editSdo = editSalesPlanRequestConverter(salesPlanLineSDO, editSalesPlanRequest);
        //总量为0明细状态变更为草稿
        if (0 == editSdo.getMonthCount()) {
            editSdo.setStatus(SalesPlanLineStatusEnum.DRAFT.getStatus());
        } else {
            editSdo.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
        }
        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(editSdo);
        Integer count = salesPlanLineEntity.doEdit();
        //触发汇总更新
        try {
            salesPlanStatService.planCollect(planId);
        } catch (Exception e) {
            log.error("修改月度计划明细,触发汇总更新失败:"+e.getMessage());
            e.printStackTrace();
        }
        if (count == 1) {
            return Result.success(salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest));
        }
        return null;
    }

    /**
     * 修改任务量
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> updateTaskCount(UpdateTaskCountRequest updateTaskCountRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(updateTaskCountRequest.getId());
        try {
            SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
            SalesPlanLineSDO salesPlanLineSdo = updateTaskCountRequestConverter(sdo, updateTaskCountRequest);
            SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(salesPlanLineSdo);
            Integer count = salesPlanLineEntity.doEdit();
            if (count > 0) {
                return Result.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(false);
    }

    @Override
    @FacadeInvoker
    public Result<Integer> updateAdjustCount(UpdateAdjustCountRequest updateAdjustCountRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(updateAdjustCountRequest.getId());
        SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(sdo.getPlanId());
        SalesPlanSDO salesPlanSDO = salesPlanQueryService.getSalesPlan(querySalesPlanRequest).getResult();
        if (Objects.isNull(salesPlanSDO)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        updateAdjustCountRequestConverter(sdo, updateAdjustCountRequest, salesPlanSDO);
        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(sdo);
        return Result.success(salesPlanLineEntity.doEdit());
    }

    @Override
    @FacadeInvoker
    public Result<String> batchImportCreateSalesPlanLine(List<SalesPlanLineSDO> salesPlanLineSdoList) {
        if (CollectionUtils.isEmpty(salesPlanLineSdoList)) {
            throw new FacadeException("OTS-02-002-02-15-010");
        }
        //planId+客户收收获地址编码+货品编码查询重复数据，重复则更新，否则新增
        Set<String> planIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getPlanId).collect(Collectors.toSet());
        Set<String> customerAddressSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = salesPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        salesPlanDetailBatchQueryRequest.setPlanIds(Lists.newArrayList(planIdSet));
        salesPlanDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddressSet));
        salesPlanDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanDetailBatchQueryRequest.setCustomerAddressIds(Lists.newArrayList(customerAddressIdSet));
        }

        Map<String, SalesPlanLineSDO> salesPlanLineMap = salesPlanLineRepository.batchQueryDetailByIds(salesPlanDetailBatchQueryRequest)
                .stream().collect(Collectors.toMap(x -> {
                    StringBuilder builder = new StringBuilder(x.getPlanId());
                    if (StringUtils.isNotBlank(x.getCustomerAddressId())) {
                        builder.append(x.getCustomerAddressId());
                    }
                    builder.append(x.getCustomerAddress()).append(x.getScItemId());
                    return builder.toString();
                }, a -> a, (a, b) -> a));

        //新增
        List<SalesPlanLineSDO> batchCreateRequestList = new ArrayList<>();
        //修改
        List<SalesPlanLineSDO> batchEditRequestList = new ArrayList<>();

        //过滤出新增还是修改
        for (SalesPlanLineSDO planLineSDO : salesPlanLineSdoList) {
            StringBuilder builder = new StringBuilder(planLineSDO.getPlanId());
            if (StringUtils.isNotBlank(planLineSDO.getCustomerAddressId())) {
                builder.append(planLineSDO.getCustomerAddressId());
            }
            builder.append(planLineSDO.getCustomerAddress()).append(planLineSDO.getScItemId());

            String key = builder.toString();
            SalesPlanLineSDO salesPlanLineSDO = salesPlanLineMap.get(key);
            planLineSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
            if (Objects.isNull(salesPlanLineSDO)) {
                batchCreateRequestList.add(planLineSDO);
            } else {
                Integer monthCount = Optional.ofNullable(planLineSDO.getMonthCount()).orElse(0);
                Integer monthFirstCount = Optional.ofNullable(planLineSDO.getMonthFirstCount()).orElse(0);
                Integer monthMiddleCount = Optional.ofNullable(planLineSDO.getMonthMiddleCount()).orElse(0);
                Integer monthLastCount = Optional.ofNullable(planLineSDO.getMonthLastCount()).orElse(0);
                Integer m1RollingPlanCount = Optional.ofNullable(planLineSDO.getM1RollingPlanCount()).orElse(0);
                Integer m2RollingPlanCount = Optional.ofNullable(planLineSDO.getM2RollingPlanCount()).orElse(0);
                Integer m3RollingPlanCount = Optional.ofNullable(planLineSDO.getM3RollingPlanCount()).orElse(0);
                Boolean isBalanced = Optional.ofNullable(planLineSDO.getIsBalanced()).orElse(true);
                BeanUtils.copyProperties(salesPlanLineSDO, planLineSDO);
                planLineSDO.setMonthCount(monthCount);
                planLineSDO.setMonthFirstCount(monthFirstCount);
                planLineSDO.setMonthMiddleCount(monthMiddleCount);
                planLineSDO.setMonthLastCount(monthLastCount);
                planLineSDO.setM1RollingPlanCount(m1RollingPlanCount);
                planLineSDO.setM2RollingPlanCount(m2RollingPlanCount);
                planLineSDO.setM3RollingPlanCount(m3RollingPlanCount);
                planLineSDO.setIsBalanced(isBalanced);
                batchEditRequestList.add(planLineSDO);
            }
        }

        Integer count = 0;
        if (batchCreateRequestList.size() > 0) {
            //新增获取并设置合同量数据
            salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(batchCreateRequestList);
            batchCreateSalesPlanLineListConverter(batchCreateRequestList);
            String batchCreateCount = salesPlanLineRepository.batchCreateSalesPlanLine(batchCreateRequestList);
            count += Integer.parseInt(batchCreateCount);
        }

        if (batchEditRequestList.size() > 0) {
            //修改获取并设置合同量数据
            salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(batchEditRequestList);
            batchCreateSalesPlanLineListConverter(batchEditRequestList);
            for (SalesPlanLineSDO salesPlanLineSDO : batchEditRequestList) {
                Integer editCount = salesPlanLineRepository.edit(salesPlanLineSDO);
                count += editCount;
            }
        }
        return Result.success(count.toString());
    }

    private void updateAdjustCountRequestConverter(SalesPlanLineSDO sdo, UpdateAdjustCountRequest updateAdjustCountRequest, SalesPlanSDO salesPlanSDO) {
        sdo.setAdjustCount(updateAdjustCountRequest.getAdjustCount());
        sdo.setAdjustMoney(updateAdjustCountRequest.getAdjustMoney());
        sdo.setBeforeAdjustMoney(updateAdjustCountRequest.getBeforeAdjustMoney());
        sdo.setMonthFirstAdjustCount(updateAdjustCountRequest.getMonthFirstAdjustCount());
        sdo.setMonthMiddleAdjustCount(updateAdjustCountRequest.getMonthMiddleAdjustCount());
        sdo.setMonthLastAdjustCount(updateAdjustCountRequest.getMonthLastAdjustCount());
//        sdo.setMonthFirstAdjustReturnCount(updateAdjustCountRequest.getMonthFirstAdjustReturnCount());
//        sdo.setMonthMiddleAdjustReturnCount(updateAdjustCountRequest.getMonthMiddleAdjustReturnCount());
//        sdo.setMonthLastAdjustReturnCount(updateAdjustCountRequest.getMonthLastAdjustReturnCount());
        sdo.calculateAdjustMoney(salesPlanSDO.getEstimateDiscount());
        sdo.setGmtModified(new Date());
    }

    /**
     * 提交保存的数据
     *
     * @param request： 筛选要被提交的计划明细数据（客户、货品）
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> submitSalesPlanLine(SubmitSalesPlanLineRequest request) {
        //批量查询月度计划明细，判断上中下旬计划量是否填报完成，更新状态
        List<Long> ids = request.getIds();
        ids.forEach(id -> {
            QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
            querySalesPlanLineRequest.setId(id);
            SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
            Boolean bool = checkStatus(sdo);
          /*  if (bool && !Objects.equals(sdo.getStatus(), SalesPlanLineStatusEnum.FINISH_FILL.getStatus())) {
                //sdo.setStatus(SalesPlanLineStatusEnum.FINISH_FILL.getStatus());
                SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(sdo);
                salesPlanLineEntity.doEdit();
                SalesPlanStatAbilityRequest statAbilityRequest = SalesPlanStatRequestConverter.submitSalesPlanLineConverter(sdo);
                Boolean aBoolean = salesPlanStatAbility.salesPlanStat(statAbilityRequest);
            }*/
        });
        return Result.success(true);
    }


//    @Nullable
//    private Result<Boolean> getSubmitResult(PageQueryPlanLineRequest pageQueryPlanLineRequest) {
//        int size = pageQueryPlanLineRequest.getSize();
//        int totalPage = getPageCount(size, salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest).getTotal());
//        AtomicInteger draftCount = new AtomicInteger();
//        List<SalesPlanLineSDO> toSubmitList = new ArrayList<>();
//        // 检查每页的数据
//        for (int page = 1; page <= totalPage; page++) {
//            pageQueryPlanLineRequest.setPage(page);
//            List<SalesPlanLineSDO> sdos = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest).getContent();
//            for (SalesPlanLineSDO sdo : sdos) {
//                if (sdo.getStatus().equals(SalesPlanLineStatusEnum.DRAFT.getStatus())) {
//                    draftCount.getAndIncrement();
//                    break;
//                }
//                toSubmitList.add(sdo);
//            }
//            //存在未完成的明细，不再循环
//            if (draftCount.get() > 0) {
//                break;
//            }
//        }
//        if (draftCount.get() > 0) {
//            return Result.failure("", "存在未完成的明细,无法保存");
//        }
//       /* List<SalesPlanLineSDO> submitStatList = toSubmitList.stream().filter(sdo -> sdo.getStatus().equals(SalesPlanLineStatusEnum.TO_BE_UPDATED.getStatus()))
//                .peek(sdo -> sdo.setStatus(SalesPlanLineStatusEnum.FINISH_FILL.getStatus())).collect(Collectors.toList());*/
//        List<SalesPlanLineSDO> submitStatList = new ArrayList<>();
//        if (CollectionUtils.isNotEmpty(submitStatList)) {
//            // 批量更新
//            Integer count = salesPlanLineRepository.batchUpdateLineStatus(submitStatList);
//            // 触发汇总
//            SalesPlanStatAbilityRequest statAbilityRequest = SalesPlanStatRequestConverter.submitSalesPlanLineListConverter(submitStatList);
//            salesPlanStatAbility.salesPlanStat(statAbilityRequest);
//            return Result.success(submitStatList.size() == count);
//        }
//        return Result.success(true);
//    }


    @Override
    @FacadeInvoker
    public Result<Integer> batchUpdateLineStatus(List<SalesPlanLineSDO> salesPlanLineSDOList) {
        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        List<Long> ids = salesPlanLineSDOList.stream().map(SalesPlanLineSDO::getId).collect(Collectors.toList());
        salesPlanDetailBatchQueryRequest.setIds(ids);
        List<SalesPlanLineSDO> salesPlanLineSDOS = salesPlanLineRepository.batchQueryDetailByIds(salesPlanDetailBatchQueryRequest);
        if (salesPlanLineSDOS.size() <= 0) {
            throw new FacadeException("OTS-02-002-00-16-004");
        }
        SalesPlanLineSDO salesPlanLineSDO1 = salesPlanLineSDOS.stream().findFirst().get();
        QuerySalesPlanRequest request = new QuerySalesPlanRequest();
        String planId = salesPlanLineSDO1.getPlanId();
        request.setId(planId);
        SalesPlanSDO salesPlanSDO = salesPlanRepository.load(request);
        if (salesPlanSDO == null) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        if (!SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus())) {
            //计划不是待锁定,不允许删除
            throw new FacadeException("OTS-02-002-00-16-005");
        }
        //是否汇总
        Boolean isSummary = false;
        for (SalesPlanLineSDO salesPlanLineSDO : salesPlanLineSDOS) {
            if (SalesPlanLineStatusEnum.FINISH.getStatus().equals(salesPlanLineSDO.getStatus())) {
                isSummary = true;
                break;
            }
        }
        Integer integer = salesPlanLineRepository.batchUpdateLineStatus(salesPlanLineSDOList);
        if (integer > 0) {
            if (isSummary) {
                //明细存在已完成状态数据,触发汇总
                salesPlanStatService.planCollect(planId);
            }
        }
        return Result.success(integer);
    }

    private SalesPlanLineSDO editSalesPlanRequestConverter(SalesPlanLineSDO originSdo, EditSalesPlanLineRequest editRequest) {
        // 构建失焦保存的sdo
        SalesPlanLineSDO editSdo = SalesPlanLineSDO.builder().build();
        BeanUtils.copyProperties(originSdo, editSdo);
        String planId = originSdo.getPlanId();
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(planId);
        Result<SalesPlanSDO> salesPlan = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        SalesPlanSDO salesPlanSDO = salesPlan.getResult();
        if (Optional.ofNullable(editRequest.getIsBalanced()).orElse(true)) {
            //传总量,需要按照三旬比例均衡计算
            if (Objects.nonNull(salesPlanSDO)) {
                BigDecimal sum = salesPlanSDO.getMonthFirstProprtion().add(salesPlanSDO.getMonthMiddleProprtion()).add(salesPlanSDO.getMonthLastProprtion());
                if (new BigDecimal(100).compareTo(sum) == 0) {
                    //月度计划有配置三旬比例均衡
                    //计划量
                    editSdo.setMonthCount(Optional.ofNullable(editRequest.getMonthCount()).orElse(0));
                    //上旬计划量
                    BigDecimal monthFirstProprtion = salesPlanSDO.getMonthFirstProprtion();
                    BigDecimal firstCount = monthFirstProprtion.multiply(new BigDecimal(Optional.ofNullable(editRequest.getMonthCount()).orElse(0)));
                    Integer monthFirstCount = firstCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    editSdo.setMonthFirstCount(monthFirstCount);

                    //下旬计划量
                    BigDecimal monthLastProprtion = salesPlanSDO.getMonthLastProprtion();
                    BigDecimal LastCount = monthLastProprtion.multiply(new BigDecimal(Optional.ofNullable(editRequest.getMonthCount()).orElse(0)));
                    Integer monthLastCount = LastCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    editSdo.setMonthLastCount(monthLastCount);

                    //中旬计划量
                    Integer monthMiddleCount = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) - (monthFirstCount + monthLastCount);
                    editSdo.setMonthMiddleCount(monthMiddleCount);
                }
            }
        } else {
            if (Optional.ofNullable(editRequest.getMonthCount()).orElse(0) != Optional.ofNullable(editRequest.getMonthFirstCount()).orElse(0) + Optional.ofNullable(editRequest.getMonthMiddleCount()).orElse(0) + Optional.ofNullable(editRequest.getMonthLastCount()).orElse(0)) {
                //不相等,抛异常
                throw new FacadeException("OTS-02-002-02-15-009");
            } else {
                //计划量
                editSdo.setMonthCount(Optional.ofNullable(editRequest.getMonthCount()).orElse(0));
                //上旬计划量
                editSdo.setMonthFirstCount(Optional.ofNullable(editRequest.getMonthFirstCount()).orElse(0));
                //中旬计划量
                editSdo.setMonthMiddleCount(Optional.ofNullable(editRequest.getMonthMiddleCount()).orElse(0));
                //下旬计划量
                editSdo.setMonthLastCount(Optional.ofNullable(editRequest.getMonthLastCount()).orElse(0));
            }
        }
        //计算折前计划金额
        long costInsuranceFreight = Objects.nonNull(originSdo.getCostInsuranceFreight()) ? originSdo.getCostInsuranceFreight() : 0;
        long beforeMonthMoney = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) * costInsuranceFreight;
        editSdo.setBeforeMonthMoney(beforeMonthMoney);
        //计算折后计划金额  折后计划金额=折前计划金额*(1-预估价格折扣率)
        editSdo.calculateMonthMoney(salesPlanSDO.getEstimateDiscount());
        //合同差量  合同差量=month_count（计划数量）-month_contract_count（合同量）
        Integer contractDifferenceCount = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) - originSdo.getMonthContractCount();
        editSdo.setContractDifferenceCount(contractDifferenceCount);
        //合同差金额 合同差金额=计划折前合同金额 -计划折前金额
        long contractDifferenceMoney = originSdo.getBeforeMonthContractMoney() - beforeMonthMoney;
        editSdo.setContractDifferenceMoney(contractDifferenceMoney);
        //计算折前满足度 折前满足度=折前计划金额/折前合同金额
        BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(beforeMonthMoney, originSdo.getBeforeMonthContractMoney());
        editSdo.setBeforeContractSatisfaction(beforeContractSatisfaction);
        //计算折后满足度  折后满足度 = 折后计划金额/折后合同金额
        BigDecimal contractSatisfaction = CalculatePercentage.retainTwo(editSdo.getMonthMoney(), originSdo.getMonthContractMoney());
        editSdo.setContractSatisfaction(contractSatisfaction);
        //修改滚动量
        editSdo.setM1RollingPlanCount(Optional.ofNullable(editRequest.getM1RollingPlanCount()).orElse(0));
        editSdo.setM2RollingPlanCount(Optional.ofNullable(editRequest.getM2RollingPlanCount()).orElse(0));
        editSdo.setM3RollingPlanCount(Optional.ofNullable(editRequest.getM3RollingPlanCount()).orElse(0));
        editSdo.setGmtModified(new Date());
        //到岸折前金额
        long outboundPrice = Objects.nonNull(originSdo.getOutboundPrice()) ? originSdo.getOutboundPrice() : 0;
        long beforeMonthOutboundMoney = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) * outboundPrice;
        editSdo.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
        //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
        editSdo.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
        return editSdo;
    }

    private SalesPlanLineSDO updateTaskCountRequestConverter(SalesPlanLineSDO sdo, UpdateTaskCountRequest updateTaskCountRequest) {
        sdo.setTaskCount(updateTaskCountRequest.getTaskCount());
        sdo.setMonthFirstTaskCount(updateTaskCountRequest.getMonthFirstTaskCount());
        sdo.setMonthMiddleTaskCount(updateTaskCountRequest.getMonthMiddleTaskCount());
        sdo.setMonthLastTaskCount(updateTaskCountRequest.getMonthLastTaskCount());
        if (sdo.getTaskCount() != null && sdo.getCostInsuranceFreight() != null) {
            //sdo.setTaskMoney(sdo.getTaskCount() * sdo.getCostInsuranceFreight());
        }
        return sdo;
    }

    private Boolean checkStatus(SalesPlanLineSDO sdo) {
        // 月度计划量为0,说明上中下旬都没有填，判断为该明细为完成填写
        return sdo.getMonthCount() != null && sdo.getMonthFirstCount() != null
                && sdo.getMonthMiddleCount() != null && sdo.getMonthLastCount() != null;
    }

    private int getPageCount(int size, int total) {
        if (total % size > 0) {
            return (total / size) + 1;
        }
        return total % size;
    }
}
